package com.yigo.prc.infra.repo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yigo.framework.http.BException;
import com.yigo.framework.http.RCodeEnum;
import com.yigo.prc.api.category.resp.CategoryTreeResp;
import com.yigo.prc.domain.category.entity.PrcCategory;
import com.yigo.prc.domain.category.repo.PrcCategoryRepo;
import com.yigo.prc.infra.repo.converter.PrcCategoryDmo2PoConverter;
import com.yigo.prc.infra.repo.dataobject.PrcCategoryPO;
import com.yigo.prc.infra.repo.mapper.PrcCategoryMapper;
import lombok.NonNull;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author chenzl
 */
@Repository
public class PrcCategoryRepoImpl implements PrcCategoryRepo {
    @Resource
    private PrcCategoryMapper prcCategoryMapper;

    @Override
    public Long countByPidAndName(@NonNull Long pid, @NonNull String categoryName) {
        LambdaQueryWrapper<PrcCategoryPO> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PrcCategoryPO::getPid, pid);
        wrapper.eq(PrcCategoryPO::getCategoryName, categoryName);
        return prcCategoryMapper.selectCount(wrapper);
    }

    @Override
    public PrcCategory save(@NonNull PrcCategory dmo) {
        PrcCategoryPO po = PrcCategoryDmo2PoConverter.INSTANCE.toPO(dmo);
        if (null == po.getId()) {
            if (prcCategoryMapper.insert(po) == 0) {
                throw new BException(RCodeEnum.PERSIST_OBJECT_ERROR);
            }
            dmo.setId(po.getId());
        } else {
            if (prcCategoryMapper.updateById(po) == 0) {
                throw new BException(RCodeEnum.PERSIST_OBJECT_ERROR);
            }
        }
        return dmo;
    }

    @Override
    public List<CategoryTreeResp> listCategory() {
        List<PrcCategoryPO> poList = prcCategoryMapper.selectList(null);
        return PrcCategoryDmo2PoConverter.INSTANCE.toTreeRespList(poList);
    }
}
